﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

using System.Windows.Forms;
using Npgsql;
using SpectationClient.Stuff;
using SpectationClient.SQLCommandBuilder;
using SpectationClient.Async;
using SpectationClient.DataBaseDescription;

namespace SpectationClient.GUI {
    public partial class SubCommandLine : Form {
        DBManager dbm;
        AGetDatabaseObject AGDBO;

        public SubCommandLine() {
            InitializeComponent();
            

        }

        public SubCommandLine(DBManager dbm) {
            InitializeComponent();
            this.Icon = Resources.Icon;
            this.dbm = dbm;
            this.AGDBO = new AGetDatabaseObject();
            this.AGDBO.GetDataTableCompleted +=new GetDataTableCompletedEventHandler(AGDBO_GetDataTableCompleted);
            #if DEBUG
                        this.RTB.Text = "select * from \"CORE\".\"LOCATIONS\"";
            #endif
        }

        void AGDBO_GetDataTableCompleted(object sender, GetDataTableCompletedEventArgs e) {
            DGV.DataSource = null;
            if(e.Cancelled) {
                RTB_Messages.Text = "Vorgang abgebrochen";
                tabControl1.SelectedTab = tabPageMessages;
            } else if(e.Error != null) {
                RTB_Messages.Text = e.Error.Message;
                tabControl1.SelectedTab = tabPageMessages;
            } else {

                int nC = e.DataTable.Columns.Count;
                int nR = e.DataTable.Rows.Count;
                if(e.UserState is TableInfo) {
                    FormHelper.initDGVColumns(DGV, e.DataTable, (TableInfo)e.UserState, null, this.dbm.Connection);
                } else {
                    FormHelper.initDGVColumns(DGV, e.DataTable);
                } 
                RTB_Messages.Clear();
                tabControl1.SelectedTab = tabPageData;
            }
           
            toggleRequestAction(false);
        }

        private void RTB_TextChanged(object sender, EventArgs e) {
            btExecute.Enabled = RTB.Text.Trim().Length > 0;
        }

        private void btExecute_Click(object sender, EventArgs e) {
            try {
            
            Regex regexSchemaTable = new Regex(@"(?<=FROM\s+)\""\w+\"".\""\w+\""(?=\s*($|ORDER|GROUP|LIMIT|WHERE|OFFSET|GROUP BY))", RegexOptions.IgnoreCase);
            Object id = System.DateTime.Now;
            String cmdText = Regex.Replace( RTB.Text, "[\n]", " ", RegexOptions.None).Trim();
                
                //Try to match with TableInfo. This helps to resolve file types 
                if(this.checkFileTypes.Checked){
                
                Match m = regexSchemaTable.Match(cmdText);
                    if(m.Success) {
                    String[] names = m.Value.Replace(@"""", "").Split(new Char[] { '.','"' });
                        if(names.Length == 2) {
                            String schema = names[0];
                            String table  = names[1];
                            if(dbm.getDataBaseInfo().ContainsTable(schema, table)) {
                                id = dbm.getDataBaseInfo()[schema][table];
                            }
                    
                        }               
                    }
                }
                
                NpgsqlCommand cmd = new NpgsqlCommand(RTB.Text.Trim(), dbm.Connection);
                toggleRequestAction(true);
                AGDBO.GetDataTableAsync(cmd, id);

            } catch(Exception ex) {
                FormHelper.ShowErrorBox(ex);
            }
        }

        private void toggleRequestAction(bool requestRunning) {
            if(requestRunning) {
                btExecute.Enabled = false;
                RTB.Cursor = Cursors.WaitCursor;
                RTB.Enabled = false;
                btCancel.Enabled = true;
            } else {
                btExecute.Enabled = RTB.Text.Trim().Length > 0;
                btCancel.Enabled = false;
                RTB.Enabled = true;
                RTB.Cursor = Cursors.Default;
            }
        
        }

        private void btCancel_Click(object sender, EventArgs e) {
            this.AGDBO.CancelAllRequest();
            
        }
    }
}
